package com.vcredit.creditcat.web.app;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.vcredit.creditcat.api.IAppTokenManager;
import com.vcredit.creditcat.api.IAuthMobileManager;
import com.vcredit.creditcat.api.ICheckLoginManager;
import com.vcredit.creditcat.api.ICreditProductManager;
import com.vcredit.creditcat.api.ICustAbilityManager;
import com.vcredit.creditcat.api.ICustAccountManage;
import com.vcredit.creditcat.api.ICustManager;
import com.vcredit.creditcat.api.ICustProductApplyManager;
import com.vcredit.creditcat.api.ICustProductManager;
import com.vcredit.creditcat.api.IMerchantProductManager;
import com.vcredit.creditcat.api.ITransitionInfoManager;
import com.vcredit.creditcat.dto.auth.IAuthItemExtManager;
import com.vcredit.creditcat.dto.creditrepository.AuthItemDto;
import com.vcredit.creditcat.dto.product.CreditCardDto;
import com.vcredit.creditcat.dto.product.MerchantProductDto;
import com.vcredit.creditcat.dto.product.ProductExpireItemDto;
import com.vcredit.creditcat.dto.product.TransitionInfo;
import com.vcredit.creditcat.dto.product.TransitionInfoVo;
import com.vcredit.creditcat.dto.speedloan.SpeedloanAuthItemDto;
import com.vcredit.creditcat.model.AuthMobile;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustAccount;
import com.vcredit.creditcat.model.CustProductApply;
import com.vcredit.creditcat.model.MerchantProduct;
import com.vcredit.creditcat.model.TextConstant;
import com.vcredit.creditcat.util.AppUtil;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.Pager;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.creditcat.vo.CarProductOutputVo;
import com.vcredit.creditcat.vo.CommitProductInputVo;
import com.vcredit.creditcat.vo.CreditCardApplyVo;
import com.vcredit.creditcat.vo.CreditCardInputVo;
import com.vcredit.creditcat.vo.FilterProductInputVo;
import com.vcredit.creditcat.vo.FilterProductInputVo2;
import com.vcredit.creditcat.vo.FilterProductOutputVo;
import com.vcredit.creditcat.vo.FilterProductOutputVo2;
import com.vcredit.creditcat.vo.IndexProductOutputVo;
import com.vcredit.creditcat.vo.JsonResult;
import com.vcredit.creditcat.vo.ProductDetailInputVo;
import com.vcredit.creditcat.vo.ProductDetailOutputVo;
import com.vcredit.creditcat.vo.ProductOutputVo;
import com.vcredit.creditcat.vo.ProductOutputVo2;
import com.vcredit.creditcat.vo.QueryTransitionInfoVO;
import com.vcredit.framework.annotation.Log;

/**
 * 贷款产品相关
 *
 * @author luquan
 *
 */
@RestController
@RequestMapping("/product")
public class CustProductController extends BaseCreditCatController {

	@Reference(version = "1.0")
	private ICustProductManager custProductManager;

	@Reference(version = "1.0")
	private IAppTokenManager appTokenService;

	@Reference(version = "1.0")
	private ICustManager custManager;

	@Reference(version = "1.0")
	private ICustManager custService;

	@Reference(version = "1.0")
	private ICustAccountManage custAccountManage;

	@Reference(version = "1.0", group = "product")
	private ICreditProductManager creditProductManager;

	@Reference(version = "1.0")
	private ICustAbilityManager custAbilityManager;

	@Reference(version = "1.0")
	private ITransitionInfoManager iTransitionInfoManager;

	@Reference(version = "1.0")
	private IAuthItemExtManager authItemExtManager;

	@Reference(version = "1.0")
	private IMerchantProductManager iMerchantProductManager;

	@Reference(version = "1.0")
	private ICheckLoginManager iCheckLoginManager;

	@Reference(version = "1.0")
	private IAuthMobileManager iAuthMobileManager;

	@Reference(version = "1.0")
	private ICustProductApplyManager iCustProductApplyManager;

	@Value("${product.detail.url}")
	private String productDetailUrl;

	/**
	 * 首页-游客
	 *
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/notLoginIndex")
	@Log
	public IndexProductOutputVo indexNotLogin(HttpServletRequest request) throws ParseException {
		// 所有热门产品
		List<MerchantProductDto> merchantProductDto = custProductManager.queryHotProduct(true);
		List<CarProductOutputVo> cars = new ArrayList<CarProductOutputVo>(); // 直通车
		List<ProductOutputVo> outputProduct = new ArrayList<ProductOutputVo>(); // 热门
		for (MerchantProductDto hot : merchantProductDto) {
			if (hot.getIsTechnical()) { // 已对接过的产品才显示在直通车
				CarProductOutputVo carProduct = new CarProductOutputVo(hot.getProductId(), hot.getProductName(),
						hot.getProductDesc(), hot.getProductIcon(), hot.getProductUri(), false, // 已经加入直通车
						0, // 欠缺的认证项数量
						null, 3);
				cars.add(carProduct);
			}

			outputProduct.add(new ProductOutputVo(hot.getProductId(), hot.getProductName(), hot.getProductDesc(),
					hot.getProductIcon(), hot.getProductUri(),
					Utility.unitMaxMin(hot.getProductMincredit(), hot.getProductMaxcredit()),
					hot.getProductApplycount(), hot.getProductRate(), false,
					hot.getCreditAmt() == null ? 0 : hot.getCreditAmt() / 100, hot.getIsHot(), hot.getSuccessRate(),
					StringUtils.isBlank(hot.getCreditExpiretime()) ? 0L
							: ConcurrentDateUtil.strToDate(hot.getCreditExpiretime()).getTime(),
					"", hot.getProductType().toString(), hot.getProductPeriod(), hot.getTag(), hot.getIsTechnical(),
					hot.getH5Url(),null));
		}
		return new IndexProductOutputVo(0, 0, cars, outputProduct);
	}

	/**
	 * 首页-用户
	 *
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/index")
	@Log
	public IndexProductOutputVo index(HttpServletRequest request) throws Exception {
		Cust cust = custManager.findById(super.getCust(request).getCustId());
		Long custId = cust.getCustId();
		// 直通车下面一排显示的产品
		List<CarProductOutputVo> undercarList = new ArrayList<CarProductOutputVo>();
		// 直通车中的产品
		List<CarProductOutputVo> car = new ArrayList<CarProductOutputVo>();
		// 所有热门产品
		List<MerchantProductDto> merchantProductDto = custProductManager.queryHotProduct(true);
		// 已经申请的产品项
		List<MerchantProductDto> applyProducts = custProductManager.queryApplyProduct(cust.getCustId());
		// 可以申请的产品,不缺认证项
		List<MerchantProductDto> canApplyProducts = custProductManager.queryProductAuth(cust.getLastProccessId(), true,
				true);
		for (MerchantProductDto can : canApplyProducts) {
			CarProductOutputVo carProduct = new CarProductOutputVo(can.getProductId(), can.getProductName(),
					can.getProductDesc(), can.getProductIcon(), can.getProductUri(), false, // 已经加入直通车
					0, // 欠缺的认证项数量
					null, 3);
			car.add(carProduct);
		}

		undercarList.addAll(car);

		// 排除直通车中已经申请的产品项
		AppUtil.excludeApplyProducts(car, applyProducts);

		// 没有通过认证的产品
		List<MerchantProductDto> noCanApplyProducts = custProductManager.queryProductAuth(cust.getLastProccessId(),
				false, true);
		for (MerchantProductDto can : noCanApplyProducts) {
			// 查询对该产品没有通过的认证项
			List<AuthItemDto> authItems = custProductManager.queryProductItem(cust.getLastProccessId(),
					can.getProductId(), false);
			CarProductOutputVo carProduct = new CarProductOutputVo(can.getProductId(), can.getProductName(),
					can.getProductDesc(), can.getProductIcon(), can.getProductUri(), false, // 未加入直通车
					authItems.size(), // 欠缺的认证项数量
					authItems, 3); // 欠缺的认证项
			undercarList.add(carProduct);
		}

		// 设置产品申请状态
		AppUtil.setProductApplyStatus(undercarList, applyProducts);

		// 热门
		List<ProductOutputVo> outputProduct = new ArrayList<ProductOutputVo>();
		for (MerchantProductDto dto : merchantProductDto) {
			Long productId = dto.getProductId();
			String status = "";
			if (dto.getIsTechnical()) {
				status = creditProductManager.getStatus(custId, productId, null, dto);
			}
			ProductOutputVo productOutputVo = new ProductOutputVo(dto.getProductId(), dto.getProductName(),
					dto.getProductDesc(), dto.getProductIcon(), dto.getProductUri(),
					Utility.unitMaxMin(dto.getProductMincredit(), dto.getProductMaxcredit()),
					dto.getProductApplycount(), dto.getProductRate(), false,
					dto.getCreditAmt() == null ? 0 : dto.getCreditAmt() / 100, dto.getIsHot(), dto.getSuccessRate(),
					StringUtils.isBlank(dto.getCreditExpiretime()) ? 0L
							: ConcurrentDateUtil.strToDate(dto.getCreditExpiretime()).getTime(),
					"", dto.getProductType().toString(), dto.getProductPeriod(), dto.getTag(), dto.getIsTechnical(),
					dto.getH5Url(),null);
			productOutputVo.setApplyDesc(status);
			outputProduct.add(productOutputVo);
		}
		return new IndexProductOutputVo(applyProducts.size(), car.size(), undercarList, outputProduct);
	}

	/***
	 * 筛选贷款产品的同时，还需获得该产品是否已在购物车中，是否已获得额度等信息
	 *
	 * @param filter
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/filter")
	@Log
	public FilterProductOutputVo filterProduct(@RequestBody FilterProductInputVo filter, HttpServletRequest request)
			throws Exception {
		Long custId = null;
		String accessToken = request.getHeader("accessToken");
		if (super.hasOnLine(request)) {
			custId = appTokenService.getCustIdFromToken(accessToken);
		}
		List<MerchantProductDto> dtos = null;
		if (filter.getFilterPattern().equals("0")) // 全部
		{
			dtos = custProductManager.queryAllProductDto();
		} else if (filter.getFilterPattern().equals("2")) // 热门贷款
		{
			dtos = custProductManager.queryHotProduct(true);
		} else if (filter.getFilterPattern().equals("3")) {// 可申请的贷款产品）
			// 认证通过可以申请的产品
			Cust managerById = custManager.findById(custId);
			dtos = custProductManager.queryProductAuth(managerById.getLastProccessId(), true, true);
			// 查询已申请的产品
			List<MerchantProductDto> applyProducts = custProductManager.queryApplyProduct(custId);
			// 去除已经申请的产品
			AppUtil.excludeApplyProducts(dtos, applyProducts);
		} else if (filter.getFilterPattern().equals("4")) // 我的申请
		{
			dtos = custProductManager.queryApplyProduct(custId);
		} else if (filter.getFilterPattern().equals("5")) // 是否技术对接
		{
			dtos = custProductManager.queryTechionalProduct(true);
		} else if (filter.getFilterPattern().equals("1")) // 筛选
		{
			dtos = custProductManager.queryFitProduct(custId, filter.getAnswers(), filter.getAppDesc());
		}
		List<ProductOutputVo> outputProduct = new ArrayList<ProductOutputVo>();
		if (null == dtos) {
			return new FilterProductOutputVo(outputProduct);
		}
		getProductVoFromDto(custId, 1L, dtos, outputProduct);
		return new FilterProductOutputVo(outputProduct);
	}

	@RequestMapping("/siftingV2")
	@Log
	public FilterProductOutputVo2 siftingProductV2(@RequestBody FilterProductInputVo2 filter, HttpServletRequest request)
			throws Exception {
		List<ProductOutputVo2>productList = new ArrayList<ProductOutputVo2>();
		ProductOutputVo2 product =new ProductOutputVo2();
		String accessToken = request.getHeader("accessToken");
		Long custId = null;
		String cashbackDesc = "贷款成功可返现"; // 用户未登录
		if (super.hasOnLine(request)) {
			custId = appTokenService.getCustIdFromToken(accessToken);
			cashbackDesc = custAbilityManager.getCustMaxAbilityValue(custId);
		}
		List<MerchantProductDto> dtos = null;
		if (filter.getFilterPattern().equals("1")) {// 筛选
			dtos = custProductManager.queryFitProduct(custId, filter.getAnswers(), null);
		}
		List<ProductOutputVo> outputProduct = new ArrayList<>();
		if (null == dtos) {
			return new FilterProductOutputVo2(productList);
		}
		setProductJumpUrl(accessToken, dtos);
		getProductVoFromDto(custId, null, dtos, outputProduct);
		setProductVoExtra(outputProduct, cashbackDesc);
	
		for (ProductOutputVo productOutputVo : outputProduct) {
			product =new ProductOutputVo2();
			product.setProductId(productOutputVo.getProductId());// 产品编号
			product.setProductName(productOutputVo.getName());// string 产品名称a
			product.setProductIcon(productOutputVo.getImgUrl());// string 产品图标
			product.setCreditLimit(productOutputVo.getLimitRange());// string 额度范围
			product.setProductDesc(productOutputVo.getProductParam());// string 产品描述 费率
			product.setProductLabel(productOutputVo.getTag());// string 产品标签
			product.setFeatureTag(productOutputVo.getFeatureTag());// string 个性标签
			product.setProductRemark(productOutputVo.getCashbackDesc());// string 产品描述
			product.setStatisticalDesc(productOutputVo.getApplyDocDesc());// string 统计描述
			product.setJumpUrl(productOutputVo.getJumpUrl());// string 跳转网址
			productList.add(product);
		} 
		Pager<ProductOutputVo2> page = new Pager<>(filter.getPageIndex(), filter.getPageSize(), productList);
		return new FilterProductOutputVo2(page.getDataList());
	}
	
	@RequestMapping("/sifting")
	@Log
	public FilterProductOutputVo siftingProduct(@RequestBody FilterProductInputVo filter, HttpServletRequest request)
			throws Exception {
		String accessToken = request.getHeader("accessToken");
		Long custId = null;
		String cashbackDesc = "贷款成功可返现"; // 用户未登录
		if (super.hasOnLine(request)) {
			custId = appTokenService.getCustIdFromToken(accessToken);
			cashbackDesc = custAbilityManager.getCustMaxAbilityValue(custId);
		}
		List<MerchantProductDto> dtos = null;
		if (filter.getFilterPattern().equals("1")) {// 筛选
			dtos = custProductManager.queryFitProduct(custId, filter.getAnswers(), filter.getAppDesc());
		}
		List<ProductOutputVo> outputProduct = new ArrayList<>();
		if (null == dtos) {
			return new FilterProductOutputVo(outputProduct);
		}
		setProductJumpUrl(accessToken, dtos);
		getProductVoFromDto(custId, null, dtos, outputProduct);
		setProductVoExtra(outputProduct, cashbackDesc);
		Pager<ProductOutputVo> page = new Pager<>(filter.getPageIndex(), filter.getPageSize(), outputProduct);
		return new FilterProductOutputVo(page.getDataList());
	}
	
	/*
	 * app接收参数需要用@RequestBody，h5不能用@RequestBody
	 */
	@RequestMapping("/siftingForH5")
	@Log
	public FilterProductOutputVo siftingProductForH5( FilterProductInputVo filter, HttpServletRequest request)
			throws Exception {
		String accessToken = request.getHeader("accessToken");
		Long custId = null;
		String cashbackDesc = "贷款成功可返现"; // 用户未登录
		if (super.hasOnLine(request)) {
			custId = appTokenService.getCustIdFromToken(accessToken);
			cashbackDesc = custAbilityManager.getCustMaxAbilityValue(custId);
		}
		List<MerchantProductDto> dtos = null;
		if (filter.getFilterPattern().equals("1")) {// 筛选
			dtos = custProductManager.queryFitProduct(custId, filter.getAnswers(), filter.getAppDesc());
		}
		List<ProductOutputVo> outputProduct = new ArrayList<>();
		if (null == dtos) {
			return new FilterProductOutputVo(outputProduct);
		}
		setProductJumpUrl(accessToken,dtos);
		getProductVoFromDto(custId, null, dtos, outputProduct);
		setProductVoExtra(outputProduct, cashbackDesc);
		Pager<ProductOutputVo> page = new Pager<>(filter.getPageIndex(), filter.getPageSize(), outputProduct);
		return new FilterProductOutputVo(page.getDataList());
	}

	/**
	 * 贷款列表设置跳转的Url
	 * 
	 * @author zhaoqi01
	 */
	private void setProductJumpUrl(String accessToken, List<MerchantProductDto> dtos) {
		if (Utility.isNullOrEmpty(dtos)) {
			return;
		}
		for (MerchantProductDto merchantProductDto : dtos) {
			if (merchantProductDto.getStar().intValue() == 0) {
				continue;
			}
			String jumpUrl = productDetailUrl + merchantProductDto.getProductId() + "/" + accessToken;
			merchantProductDto.setProductUri(jumpUrl);
		}
	}

	private void setProductVoExtra(List<ProductOutputVo> outputProduct, Object... objects) {
		for (ProductOutputVo vo : outputProduct) {
			if (54 == vo.getProductId() || 55 == vo.getProductId()) {
				continue;
			}
			vo.setCashbackDesc(objects[0].toString());
		}
	}

	private void getProductVoFromDto(Long custId, Long type, List<MerchantProductDto> dtos,
			List<ProductOutputVo> outputProduct) throws Exception {
		for (MerchantProductDto dto : dtos) {
			if (dto.getAuditResult() != null && dto.getAuditResult() == 22) {
				dto.setAuditResult(2);
			}
			Long productId = dto.getProductId();
			String status = "";
			String frozenTime = "";
			if (dto.getIsTechnical() && ObjectUtils.notEqual(null, custId)) {
				status = creditProductManager.getStatus(custId, productId, type, dto);
				CustProductApply applyedItem = creditProductManager.getAppliedItem(custId, productId);
				frozenTime = applyedItem == null ? "" : applyedItem.getCreditApplyTime();
			}
			String AuditResult = "";
			if (dto.getAuditResult() != null) {
				if (dto.getAuditResult() > 7) { // 统一为授信后状态8
					AuditResult = "8";
				} else {
					AuditResult = dto.getAuditResult().toString();
				}
			}

			ProductOutputVo productOutputVo = new ProductOutputVo(dto.getProductId(), dto.getProductName(),
					dto.getProductDesc(), dto.getProductIcon(), dto.getProductUri(),
					Utility.unitMaxMinYUAN(dto.getProductMincredit(), dto.getProductMaxcredit()),
					dto.getProductApplycount(), dto.getProductRate(), false,
					dto.getCreditAmt() == null ? 0 : dto.getCreditAmt() / 100, false, dto.getSuccessRate(),
					StringUtils.isBlank(dto.getCreditExpiretime()) ? 0L
							: ConcurrentDateUtil.strToDate(dto.getCreditExpiretime()).getTime(),
					AuditResult, dto.getProductType().toString(), dto.getProductPeriod(), dto.getTag(),
					dto.getIsTechnical(), dto.getH5Url(),dto.getFeatureTag());
			// 增加费率
			StringBuilder sb = new StringBuilder();
			// 费率拼接
			sb = sb.append(TextConstant.FEI_LV).append(TextConstant.MAO_HAO).append(dto.getProductRate());
			// 期限拼接
			sb = sb.append(TextConstant.SHU_GANG).append(TextConstant.TERM).append(TextConstant.MAO_HAO)
					.append(dto.getProductPeriod());
			productOutputVo.setProductParam(sb.toString());
			productOutputVo.setApplyDesc(status);
			productOutputVo.setFrozenTime(frozenTime);
			productOutputVo.setApplyDocDesc(dto.getProductApplycount()+TextConstant.CHENG_GONG_SHEN_QING);
			outputProduct.add(productOutputVo);
			
		}
	}

	/***
	 * 获取产品详情,设置产品识别号，获取相关产品贷款信息
	 *
	 * @param input
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/queryDetail")
	@Log
	public ProductDetailOutputVo queryProductDetail(@RequestBody ProductDetailInputVo input, HttpServletRequest request)
			throws Exception {
		Long productId = Long.valueOf(input.getProductId());
		Cust cust = custManager.findById(super.getCust(request).getCustId());
		MerchantProductDto dto = custProductManager.queryProductById(productId, cust.getCustId());

		List<SpeedloanAuthItemDto> speedloanAuthItems = authItemExtManager.getSpeedloanAuthItemsByCustAndProduct(cust,
				productId);

		List<AuthItemDto> authItemDto = this.speedloanAuthItemDtosToAuthItemDtos(speedloanAuthItems);

		// 设置审批结果
		this.setAuditResult(dto, authItemDto);

		ProductOutputVo product = null;
		if (dto != null) {
			product = new ProductOutputVo(dto.getProductId(), dto.getProductName(), dto.getProductDesc(),
					dto.getProductIcon(), dto.getProductUri(),
					Utility.unitMaxMin(dto.getProductMincredit(), dto.getProductMaxcredit()),
					dto.getProductApplycount(), dto.getProductRate(), false,
					dto.getCreditAmt() == null ? 0 : dto.getCreditAmt() / 100, dto.getIsHot(), dto.getSuccessRate(),
					StringUtils.isBlank(dto.getCreditExpiretime()) ? 0L
							: ConcurrentDateUtil.strToDate(dto.getCreditExpiretime()).getTime(),
					dto.getAuditResult() == null ? "" : dto.getAuditResult().toString(),
					dto.getProductType().toString(), dto.getProductPeriod(), dto.getTag(), dto.getIsTechnical(),
					dto.getH5Url(),null);
			// wichell 20170719 增加产品详情接口下次申请时间字段
			if (StringUtils.isNotBlank(dto.getCreditApplyTime())) {
				product.setCanApplyTime(ConcurrentDateUtil.getDate(dto.getCreditApplyTime()).getTime());
			}
			String status = "";
			if (dto.getIsTechnical() && ObjectUtils.notEqual(null, cust.getCustId())) {
				status = creditProductManager.getStatus(cust.getCustId(), dto.getProductId(), null, dto);
				product.setApplyDesc(status);
			}
			// 申请条件
			product.getApplyConditionList().add(dto.getProductApplycondition());
		}
		return new ProductDetailOutputVo(product, authItemDto);
	}

	private List<AuthItemDto> speedloanAuthItemDtosToAuthItemDtos(List<SpeedloanAuthItemDto> speedloanAuthItems) {
		List<AuthItemDto> result = new ArrayList<AuthItemDto>();

		for (SpeedloanAuthItemDto speedloanAuthItemDto : speedloanAuthItems) {
			AuthItemDto authItemDto = new AuthItemDto();
			authItemDto.setFrontId(speedloanAuthItemDto.getItemCode() + "");
			authItemDto.setName(speedloanAuthItemDto.getItemName());
			authItemDto.setDesc(speedloanAuthItemDto.getItemDesc());
			authItemDto.setIconUrl(speedloanAuthItemDto.getItemIcon());
			authItemDto.setIsFinish("1".equals(speedloanAuthItemDto.getStatus()) ? 1 : 0);

			result.add(authItemDto);
		}

		return result;
	}

	/**
	 * 设置审批状态 如果为3表示未申请过，判断认证是否完成，已完成设置为4表示认证已通过
	 *
	 * @param dto
	 * @param authItems
	 */
	private void setAuditResult(MerchantProductDto dto, List<AuthItemDto> authItems) {
		if (null == dto.getAuditResult() || dto.getAuditResult() == 3) {
			boolean authComplete = true;
			for (AuthItemDto authItemDto : authItems) {
				if (authItemDto.getIsFinish() == 0) {
					authComplete = false;
					break;
				}
			}
			if (authComplete) {
				dto.setAuditResult(4);
			} else {
				dto.setAuditResult(3);
			}
		}
	}

	/**
	 * 提交申请,一键申请贷款产品
	 *
	 * @param input
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/commit")
	@Log
	public JsonResult<ProductExpireItemDto> commit(@RequestBody CommitProductInputVo input, HttpServletRequest request)
			throws Exception {
		Map<String, String> otherParams = new HashMap<String, String>();
		otherParams.put("deviceNo", input.getDeviceNo());
		otherParams.put("phoneModel", input.getPhoneModel());
		otherParams.put("operatingSys", input.getOperatingSys());
		Long custId = super.getCust(request).getCustId();
		ProductExpireItemDto result = creditProductManager.applyCommit(custId, Long.parseLong(input.getProductIds()),
				otherParams);
		return JsonResult.SuccessResponse(result);
	}

	/**
	 * 提交申请,一键申请贷款产品 新版本返回
	 *
	 * @param input
	 * @param request
	 * @return
	 * @throws Exception
	 */
	// @RequestMapping("/commits")
	// @Log
	// public JsonResult<ProductApplyResultDto> commits(@RequestBody
	// CommitProductInputVo input,
	// HttpServletRequest request) throws Exception {
	// Map<String, Object> otherParams = new HashMap<String, Object>();
	// otherParams.put("deviceNo", input.getDeviceNo());
	// otherParams.put("phoneModel", input.getPhoneModel());
	// otherParams.put("operatingSys", input.getOperatingSys());
	// Long custId = super.getCust(request).getCustId();
	// ProductApplyResultDto result = creditProductManager.apply(custId,
	// Long.parseLong(input.getProductIds()),
	// otherParams);
	// return JsonResult.SuccessResponse(result);
	// }

	/**
	 * 办信用卡的信用卡列表
	 *
	 * @param input
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/recommendCard")
	@Log
	public Object getRecommendCard(@RequestBody CreditCardInputVo input, HttpServletRequest request) throws Exception {
		Long custId = null;
		if (super.hasOnLine(request)) {
			String accessToken = request.getHeader("accessToken");
			custId = appTokenService.getCustIdFromToken(accessToken);
		}
		List<CreditCardDto> list = custProductManager.recommendCard(custId, input.getApplyKind(), input.getAppDesc());

		return new CreditCardApplyVo(list);
	}

	/**
	 * 信息引导
	 * 
	 * @param productId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping("/queryTransitionInfo")
	public JsonResult queryTransitionInfo(@RequestBody QueryTransitionInfoVO obj, HttpServletRequest request)
			throws Exception {

		// token
		String token = obj.getAccessToken();
		if (null == token) {
			token = request.getHeader("accessToken");
			if (null == token) {
				token = request.getParameter("accessToken");
			}
		}

		if (null == token || token.trim().length() == 0) {
			return JsonResult.ErrorResponse("token未被识别");
		} else {
			if (!iCheckLoginManager.checkLogin(token)) {
				return JsonResult.ErrorResponse("token超时");
			}
		}

		// productId
		String productId = obj.getProductId();
		if (null == productId) {
			productId = request.getParameter("productId");
		}
		if (null == productId || productId.trim().length() == 0) {
			return JsonResult.ErrorResponse("产品ID不能为空");
		}

		// 获取客户数据
		String mobile = "";
		Long custId = appTokenService.getCustIdFromToken(token);
		if (productId.equals("25")) {
			CustAccount custAccount = custAccountManage.findById(custId);
			mobile = custAccount.getUserName();
		} else {
			Cust cust = custManager.findById(custId);
			AuthMobile authMobile = iAuthMobileManager.findAuthMobile(cust, Long.valueOf(productId));
			if (null != authMobile && authMobile.getResultStatus().equals(4)) {
				String expired_time = authMobile.getExpiredTime();

				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
				String date1 = df.format(new Date());// new Date()为获取当前系统时间

				int bs = Utility.compareDate(date1, expired_time);
				// if(bs<0){// 系统时间在过期时间之前
				mobile = authMobile.getMobile();
				// }else{
				// return JsonResult.ErrorResponse("手机认证已过期");//
				// .SuccessResponse(result);
				// }
			} else {
				CustAccount custAccount = custAccountManage.findById(custId);
				mobile = custAccount.getUserName();
				// return JsonResult.ErrorResponse("未获取到手机认证数据");
			}
		}
		if (null == mobile || mobile.length() == 0) {
			return JsonResult.ErrorResponse("未获取到手机号");// .SuccessResponse(result);
		}

		TransitionInfo transitionInfo = new TransitionInfo();
		// 查询并设置密码设置手机号&文案数据
		List<TransitionInfo> list = new ArrayList<TransitionInfo>();
		list = iTransitionInfoManager.queryTransitionInfo(obj.getProductId(), custId, mobile);
		if (null == list || list.size() == 0) {
			return JsonResult.ErrorResponse("未获取到密码数据");// .SuccessResponse(result);
		} else {
			transitionInfo = list.get(0);
		}

		// 获取并设置product_url
		String productUrl = "";
		Long[] ids = new Long[] { Long.parseLong(productId) };
		List<MerchantProduct> list2 = iMerchantProductManager.findByIds(ids);
		if (null == list2 || list2.size() == 0) {
			return JsonResult.ErrorResponse("未获取到产品数据");// .SuccessResponse(result);
		} else {
			MerchantProduct merchantProduct = list2.get(0);
			productUrl = merchantProduct.getProductUri();
		}
		transitionInfo.setProductUrl(productUrl);

		// 获取并设置额度
		CustProductApply custProductApply = iCustProductApplyManager.findNewApplyProduct(Long.parseLong(productId),
				custId);
		if (null != custProductApply && custProductApply.getCreditAmt().toString().trim().length() > 0) {
			transitionInfo.setCreditAmt(custProductApply.getCreditAmt().toString());
		} else {
			transitionInfo.setCreditAmt("0");
		}

		// 组装返回
		TransitionInfoVo transitionInfoVo = new TransitionInfoVo();
		transitionInfoVo.setTransitionInfo(transitionInfo);
		return JsonResult.SuccessResponse(transitionInfoVo);
	}

}
